package com.bincent.support;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPool {
    /**
     * 核心线程池大小
     */
    private static final int corePoolSize = 5;

    /**
     * 最大线程池大小
     */
    private static final int maximumPoolSize = 10;

    /**
     * 工作队列
     */
    private static ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(500);

    private static ThreadPool instance = new ThreadPool();

    private ExecutorService executorService;

    private ThreadPool() {
        executorService = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 30, TimeUnit.MINUTES, workQueue, new ThreadFactory() {
            private final AtomicInteger threadNumber = new AtomicInteger(1);
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("ThreadPoolUtil-thread-" + threadNumber.getAndIncrement());
                return thread;
            }
        }, new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                try {
                    executor.getQueue().put(r);
                } catch (Exception e) {
                    // LOGGER.error("线程放入队列出错", e);
                }
            }
        });
    }

    public static ThreadPool getInstance(){
        return instance;
    }

    /**
     * 执行入口
     * @param command
     * @author dingkai(kai.d@51offer.com)
     * 2016年6月20日 上午11:02:20
     */
    public void execute(Runnable command) {
        executorService.execute(command);
    }

    public void destory(){
        if(executorService != null){
            executorService.shutdownNow();
        }
    }
}
